package com.example.tianling.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.tianling.common.request.FileReq;
import com.example.tianling.common.request.OpenReq;
import com.google.gson.Gson;
import okhttp3.OkHttpClient;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;


import java.io.File;
import java.io.FileInputStream;
import java.util.List;

@Component
public class fileToWord {
    private static String APP_ID = "19d678a8";
    private static String API_SECRET = "ZThlYzQzOWI1OWNlY2M0Yjc2MTY4YTVk";
    private static String API_KEY = "c82663913c6e3d870962df86a64922e9";

    private static String FILE_URL_PREFIX = "https://upload-ost-api.xfyun.cn/file"; // 上传文件的地址开头

    private static String OPEN_URL_PREFIX = "https://ost-api.xfyun.cn/v2"; // 创建、查询任务的地址开头
    private static OkHttpClient client = new OkHttpClient.Builder().build();
    private static final Gson gson=new Gson();
//    private static final String AUDIO_PATH="D:\\新建文件夹\\speed_transcription_java_demo\\audioExample\\audio_sample_little.wav"; // 在此指定音频文件路径
    private static final int SLICE_SIZE = 15728640;// 15M，每块范围 5M~32M

    public String getword(File audio,String fileName,String requestId) throws Exception {
        String result = "";
//        File audio = new File(AUDIO_PATH); // 需极速转写的音频文件
        FileInputStream fis = new FileInputStream(audio);
        FileCaller fileCaller = FileCaller.builder().apiKey(API_KEY).apiSecret(API_SECRET).client(client).ulrPrefix(FILE_URL_PREFIX).build();
        JSONObject jsonObjectUploadRespOrCompleteResp = null;
        if(audio.length()<31457280){
            /** 1.1 如果是小文件走单个上传接口，建议不大于30M */
            FileResp<FileResp.UploadData> uploadResp = fileCaller.fileUpload(FileReq.Upload.builder().
                    appId(APP_ID).
                    fileName(fileName).
                    requestId(requestId).
                    data(IOUtils.toByteArray(fis))
                    .build());

            jsonObjectUploadRespOrCompleteResp= JSON.parseObject(JSON.toJSONString(uploadResp.getData()));
        }
        /** 3. 创建任务 */
        OpenCaller openCaller = OpenCaller.builder().apiKey(API_KEY).apiSecret(API_SECRET).
                client(client).ulrPrefix(OPEN_URL_PREFIX).build();
        OpenResp createResp = openCaller.create(OpenReq.Create.builder().
                common(OpenReq.Common.builder().appId(APP_ID).build()).
                business(OpenReq.Business.builder().
                        requestId(requestId).
                        // callbackUrl("http://IP:端口号/xxx").
                                accent("mandarin").
                        language("zh_cn").
                        domain("pro_ost_ed").
                        build()).
                data(OpenReq.Data.builder().audioUrl(jsonObjectUploadRespOrCompleteResp.get("url").toString()). // 上传文件或分块上传完成返回的url
                        encoding("raw").format("audio/L16;rate=16000").audioSrc("http").build()).
                build());

        JSONObject jsonObjectCreateResp=JSON.parseObject(JSON.toJSONString(createResp.getData()));

        /** 4. 查询任务 */
        OpenResp queryResp = openCaller.query(OpenReq.Query.builder().
                common(OpenReq.Common.builder().appId(APP_ID).build()).
                business(OpenReq.QueryBusiness.builder().taskId(jsonObjectCreateResp.get("task_id").toString()).build()). // 创建任务返回的task_id
                        build());

        JSONObject jsonObjectQueryResp=JSON.parseObject(JSON.toJSONString(queryResp.getData()));
        while(true){
            if(jsonObjectQueryResp.get("task_status").equals("5")){
                System.out.println("极速转写-最终结果==>：任务已取消..."); // 控制台打印取消信息
                break; // 跳出循环
            }else if(jsonObjectQueryResp.get("task_status").equals("3")||jsonObjectQueryResp.get("task_status").equals("4")){
                // System.out.println("极速转写-最终结果==>：\n"+queryResp); // 控制台打印最终转写结果

                JsonParse jsonParse=gson.fromJson(jsonObjectQueryResp.toJSONString(), JsonParse.class);
                List<Lattice> latticeList=jsonParse.result.lattice;
                for(int i=0;i<latticeList.size();i++){
                    Lattice tempLattice=latticeList.get(i);
                    // String rl=tempLattice.json_1best.st.rl;
                    List<Rt> rtList=tempLattice.json_1best.st.rt;
                    for(int j=0;j<rtList.size();j++){
                        Rt tempRt=rtList.get(j);
                        List<Ws> wsList=tempRt.ws;
                        for(int k=0;k<wsList.size();k++){
                            Ws tempWs=wsList.get(k);
                            List<Cw> cwList=tempWs.cw;
                            for(int l=0;l<cwList.size();l++){
                                Cw tempCw=cwList.get(l);

                                result+= tempCw.w;
                            }
                        }
                    }
                }
                break; // 跳出循环
            }else{
                Thread.sleep(2000); // 两秒查询一次
                // 再次查询任务
                queryResp = openCaller.query(OpenReq.Query.builder().
                        common(OpenReq.Common.builder().appId(APP_ID).build()).
                        business(OpenReq.QueryBusiness.builder().taskId(jsonObjectCreateResp.get("task_id").toString()).build()). // 创建任务返回的task_id
                                build());
                jsonObjectQueryResp=JSON.parseObject(JSON.toJSONString(queryResp.getData()));

            }
        }
        return result;
    }
        public class JsonParse{
            String task_id;
            String task_status;
            String task_type;
            String force_refresh;
            Result result;
        }
        class Result{
            List<Lattice> lattice;
        }
        class Lattice{
            Json_1best json_1best;
        }
        class Json_1best{
            St st;
        }
        class St{
            List<Rt> rt;
            String rl;
        }
        class Rt{
            List<Ws> ws;
        }
        class Ws{
            List<Cw> cw;
        }
        class Cw{
            String w;
        }
    }
